package com.siecom.transport.usbport;

import android.content.Context;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Toast;

import com.google.protobuf.InvalidProtocolBufferException;
import com.siecom.hostservice.MainActivity;
import com.siecom.proto.Message;
import com.siecom.tool.ByteTool;
import com.siecom.tool.LogUtil;
import com.siecom.transport.CommServer;
import com.siecom.transport.Distribution;
import com.siecom.transport.handler.ServiceHandler;
import com.siecom.transport.serialport.SerialServer;
import com.siecom.transport.usbport.receiver.OpenAccessoryReceiver;
import com.siecom.transport.usbport.receiver.UsbDetachedReceiver;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UsbServer extends CommServer {

    private static final String TAG = UsbServer.class.getSimpleName();
    private ExecutorService mThreadPool;
//    private OpenAccessoryReceiver mOpenAccessoryReceiver;
//    private UsbDetachedReceiver mUsbDetachedReceiver;
    private ParcelFileDescriptor mParcelFileDescriptor;
    private FileInputStream       mFileInputStream;
    private FileOutputStream      mFileOutputStream;
    public UsbManager mUsbManager;

    public static int mUSbConnectState = -1;  // 0 已经连接
    private HashMap<Integer, ServiceHandler> handlerMap = Distribution.handlerMap;

    public UsbServer(){
         mUsbManager = (UsbManager) MainActivity.context.getSystemService(Context.USB_SERVICE);

    }

    /**
     * 打开Accessory模式
     *
     * @param usbAccessory
     */
    public boolean openAccessory(UsbAccessory usbAccessory) {
        mParcelFileDescriptor = mUsbManager.openAccessory(usbAccessory);
        LogUtil.e(TAG,"mParcelFileDescriptor=" + mParcelFileDescriptor);

        if (mParcelFileDescriptor != null) {
            FileDescriptor fileDescriptor = mParcelFileDescriptor.getFileDescriptor();
            mFileInputStream = new FileInputStream(fileDescriptor);
            mFileOutputStream = new FileOutputStream(fileDescriptor);
            LogUtil.e(TAG,"连接成功！！！");
            mUSbConnectState = 0;
            return true;
        }else {
            return false;
        }
    }

    private byte[]       mBytes        = new byte[1024*11];
    public void listenFromUsb(){
        Toast.makeText(MainActivity.context,"listenFromUsb!!",Toast.LENGTH_SHORT).show();
        LogUtil.e(TAG,"listenFromUsb！！！");
        if(mThreadPool == null){
            mThreadPool = Executors.newFixedThreadPool(2);
        }
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                isInterrupted = false;

                        int i = 0;
                        while (  !isInterrupted) {
                            try {
                                LogUtil.e(TAG,"i 1==" + i);
                                i = mFileInputStream.read(mBytes);
                                LogUtil.e(TAG,"读取后 i==" + i + " ---- " + new String(mBytes).trim());
                            } catch (IOException e) {
                                e.printStackTrace();
                                break;
                            }
                            byte b[] = new byte[i];
                            System.arraycopy(mBytes,0,b,0,i);
//                            LogUtil.e(TAG,"接收成功！！！" + ByteTool.byte2hex(b));
                            Message.siecomproto msg ;//= Message.siecomproto.parseDelimitedFrom(mFileInputStream);
                            try {
                                msg = Message.siecomproto.parseFrom(b);
                                int module = msg.getModule();
//                                Log.e(TAG, "USB cmd==" + msg.getCmd());
                                if (handlerMap.containsKey(module)) {
                                    ServiceHandler handler = handlerMap.get(module);
                                    handler.onReceive(UsbServer.this, msg,"");
                                }

                            }
                            catch (InvalidProtocolBufferException e) {
                                e.printStackTrace();
                                Log.e(TAG, "InvalidProtocolBufferException ==" + e.getMessage());
                            }

                        }


//                    LogUtil.e(TAG,"isInterrupted ==" + isInterrupted);
//                    try {
//
//                        int len = mFileInputStream.available();
//                        LogUtil.e(TAG,"len ==" + len);
//                        byte b[] = new byte[len];
//                        LogUtil.e(TAG,"接收成功！！！" + new String(b));
//                        Message.siecomproto msg = Message.siecomproto.parseDelimitedFrom(mFileInputStream);
//                        int module = msg.getModule();
//                        Log.e("module:", "USB ==" + module);
//                        if (handlerMap.containsKey(module)) {
//                            ServiceHandler handler = handlerMap.get(module);
//                            handler.onReceive(UsbServer.this, msg);
//                        }
////                            i = mFileInputStream.read(mBytes);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        break;
//                    }
//

            }
        });

    }

    public void closeAccessory(){
        mUSbConnectState = -1;

        isInterrupted = true;
        if(mFileInputStream != null){
            try {
                mFileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mFileInputStream = null;
        }

        if(mFileOutputStream != null){
            try {
                mFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mFileOutputStream = null;
        }

        if(mParcelFileDescriptor != null){
            try {
                mParcelFileDescriptor.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mParcelFileDescriptor = null;
        }
        if (mThreadPool!= null){
            mThreadPool.shutdown();
            mThreadPool = null;
            LogUtil.e(TAG,"mThreadPool.shutdown ");
        }

    }

    @Override
    public void sendToRemote(Message.siecomproto msg) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    LogUtil.e(TAG,"USB 发送的内容：" + msg.toString());
                    mFileOutputStream.write(msg.toByteArray());
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtil.e(TAG,"USB send exception:" + e.getMessage());

                }
            }
        });


    }
}
